import json

from django.http import HttpResponse
from rest_framework.views import APIView

from pyecharts.charts import Map
from pyecharts import options as opts

from apps.message_form.models import Message


def response_as_json(data):
    json_str = json.dumps(data)
    response = HttpResponse(
        json_str,
        content_type="application/json",
    )
    response["Access-Control-Allow-Origin"] = "*"
    return response


def json_response(data, code=200):
    data = {
        "code": code,
        "msg": "success",
        "data": data,
    }
    return response_as_json(data)


def json_error(error_string="error", code=500, **kwargs):
    data = {
        "code": code,
        "msg": error_string,
        "data": {}
    }
    data.update(kwargs)
    return response_as_json(data)


JsonResponse = json_response
JsonError = json_error



def map() -> Map:
    all_messages = Message.objects.all()
    c = (
        Map()
            .add("藏药", [list(Message.objects.values_list('value', flat=True))], "china")
            .set_global_opts(title_opts=opts.TitleOpts(title="分布图"))
            .render("./apps/map/templates/index.html")
    )
    return c


class MapView(APIView):
    def get(self, request, *args, **kwargs):
        return JsonResponse(json.loads(map()))


class IndexView(APIView):
    def get(self, request, *args, **kwargs):
        return HttpResponse(content=open("./apps/map/templates/index.html").read())